import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { ZRequestInterceptors, InterceptorConfig, QueueType } from './type'
import { ElLoading } from 'element-plus'
import { ILoadingInstance } from 'element-plus/lib/components/loading/src/loading.type'
import storage from '@/utils/storage'
const DEFAULT_LOADING = true

class ZRequest {
  instance: AxiosInstance
  interceptors?: ZRequestInterceptors
  isShowLoading: boolean
  loading?: ILoadingInstance
  queue: QueueType
  constructor(config: InterceptorConfig) {
    this.instance = axios.create(config)
    this.isShowLoading = config.showLoading ?? DEFAULT_LOADING
    this.interceptors = config.interceptors
    this.queue = {}
    // 对单个实例的拦截
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )
    // 全局拦截
    this.instance.interceptors.request.use(
      (config) => {
        console.log('全局拦截')
        if (this.isShowLoading && Object.keys(this.queue).length === 0) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在请求数据...',
            background: 'rgba(0,0,0,0.5)'
          })
        }
        if (config.url) {
          this.queue[config.url] = config.url
        }
        // 设置token
        const token = storage.getStorage('token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        this.hideLoading(res)
        const data = res.data
        if (data.returnCode === '-1001') {
          console.log('请求数据失败~')
        } else {
          return data
        }
      },
      (err) => {
        this.hideLoading(err)
        if (err.response.status === 404) {
          console.log('404的错误~')
        }
        return err
      }
    )
  }
  hideLoading(res: any) {
    if (res.config?.url) {
      delete this.queue[res.config.url]
    }
    if (Object.keys(this.queue).length === 0) {
      this.loading?.close()
    }
  }
  request<T>(config: InterceptorConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }
      // 判断是否需要loading
      if (config.showLoading === false) {
        this.isShowLoading = config.showLoading
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          // 重置loading
          this.isShowLoading = DEFAULT_LOADING
          resolve(res)
        })
        .catch((err) => {
          this.isShowLoading = DEFAULT_LOADING
          reject(err)
          return err
        })
    })
  }
  get<T>(config: InterceptorConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' })
  }
  post<T>(config: InterceptorConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' })
  }
  detele<T>(config: InterceptorConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' })
  }
  patch<T>(config: InterceptorConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' })
  }
}

export default ZRequest
